package com.irdstudio.efp.esb.api.rest.psd.query;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.esb.api.bean.psd.query.req.NlsPsdPreCreditResultQueryReqBean;
import com.irdstudio.efp.esb.api.bean.psd.query.resp.NlsPsdPreCreditResultQueryRespBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.GroupeInterface;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.service.facade.psd.PreNlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.psd.PreNlsCreditInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;

/**
 * 需求编号：【2019D1218】（普税贷需求）
 * 问题编号：【2019D1218】（普税贷预授信申请信息查询）
 * 开发人员：【ludayong】
 * 创建日期：【2019/12/16 10:11】
 * 功能描述：
 */

@RestController
@RequestMapping("esb")
public class NlsPsdPreCreditResultQueryController implements EsbController {
    /**
     * 日志信息
     */
    private final Logger logger = LoggerFactory.getLogger(NlsPsdPreCreditResultQueryController.class);

    @PostMapping("/SERVICE_30230003_17")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult bindingResult1,
                                     @Validated({GroupeInterface.psd.class}) @ModelAttribute("nlsPsdPreCreditResultQueryReqBean") NlsPsdPreCreditResultQueryReqBean nlsPsdPreCreditResultQueryReqBean, BindingResult bindingResult2, Exception exception) {
        // 渠道申请号
        String chanAppNo = nlsPsdPreCreditResultQueryReqBean.getChanAppNo();
        // 预授信申请信息查询响应信息
        NlsPsdPreCreditResultQueryRespBean nlsPsdPreCreditResultQueryRespBean = new NlsPsdPreCreditResultQueryRespBean();
        try {
            logger.info("======>调用接口【" + chanAppNo + "_30230003_17】开始<======");
            // 参数校验
            validateBean(esbReqServiceBean, bindingResult1, nlsPsdPreCreditResultQueryReqBean, bindingResult2, exception, logger);
            // 设置系统头对象
            setSysHeadFieldThreadLocal(esbReqServiceBean);

            // 预授信申请信息入参
            PreNlsCreditInfoVO inPreNlsCreditInfoVo = new PreNlsCreditInfoVO();
            // 渠道申请号
            inPreNlsCreditInfoVo.setChannelApplyNo(chanAppNo);
            // 预授信申请信息查询信息
            PreNlsCreditInfoVO queryPreNlsCreditInfoVo = preNlsCreditInfoService.queryByChannelApplyNo(inPreNlsCreditInfoVo);
            // 预授信申请信息查询成功返回报文
            return successHandler(esbReqServiceBean, nlsPsdPreCreditResultQueryRespBean, queryPreNlsCreditInfoVo);
        } catch (ESBException e) {
            logger.error("普税贷预授信申请信息查询接口出现异常，异常信息：", e.getMessage());
            e.printStackTrace();
            return failureHandler(esbReqServiceBean, nlsPsdPreCreditResultQueryRespBean, e, EsbRetCodeStandard.JKYDCSJYBTG);
        } catch (Exception e) {
            logger.error("普税贷预授信申请信息查询接口出现异常，异常信息：", e.getMessage());
            e.printStackTrace();
            return failureHandler(esbReqServiceBean, nlsPsdPreCreditResultQueryRespBean, e, EsbRetCodeStandard.SJCLYC);
        } finally {
            logger.info("======>调用接口【" + chanAppNo + "_30230003_17】结束<======");
        }
    }

    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("获取ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    @ModelAttribute("nlsPsdPreCreditResultQueryReqBean")
    public NlsPsdPreCreditResultQueryReqBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("获取ESB请求体！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, NlsPsdPreCreditResultQueryReqBean.class);
    }

    /**
     * 需求编号：【2019D1218】（普税贷需求）
     * 问题编号：【2019D1218】（普税贷预授信申请信息查询成功返回信息）
     * 开发人员：【ludayong】
     * 创建日期：【2019/12/16 15:55】
     * 功能描述：
     * 修改日期：【2019/12/16 15:55】
     * 修改描述：
     */
    public EsbRespServiceBean successHandler(EsbReqServiceBean esbReqServiceBean, NlsPsdPreCreditResultQueryRespBean nlsPsdPreCreditResultQueryRespBean, PreNlsCreditInfoVO queryPreNlsCreditInfoVo) throws Exception{
        // 返回代码
        nlsPsdPreCreditResultQueryRespBean.setRetCd(ESBConstant.SUCCESS);
        // 返回信息
        nlsPsdPreCreditResultQueryRespBean.setRetMsg("查询成功");
        if(Objects.nonNull(queryPreNlsCreditInfoVo)){
            // 预授信申请流水号
            nlsPsdPreCreditResultQueryRespBean.setPreCrAppSrlNo(queryPreNlsCreditInfoVo.getApplySeq());
            // 产品代码
            nlsPsdPreCreditResultQueryRespBean.setPdCd(queryPreNlsCreditInfoVo.getPrdId());
            // 渠道申请号
            nlsPsdPreCreditResultQueryRespBean.setChanAppNo(queryPreNlsCreditInfoVo.getChannelApplyNo());
            // 纳税人识别号
            nlsPsdPreCreditResultQueryRespBean.setTaxpyrIdntfNo(queryPreNlsCreditInfoVo.getTaxIdentificationNumber());
            // 企业名称
            nlsPsdPreCreditResultQueryRespBean.setEntpNm(queryPreNlsCreditInfoVo.getEnterpriseName());
            // 企业社会信用代码
            nlsPsdPreCreditResultQueryRespBean.setSoclCrdtCd(queryPreNlsCreditInfoVo.getSocialCreditCode());
            // 企业注册地址
            nlsPsdPreCreditResultQueryRespBean.setEntpRgstAddr(queryPreNlsCreditInfoVo.getRegistration());
            // 推荐人工号
            nlsPsdPreCreditResultQueryRespBean.setRefrId(queryPreNlsCreditInfoVo.getRecommenderAccount());
            // 推荐人所属机构号
            nlsPsdPreCreditResultQueryRespBean.setRefrBlngBrchNo(queryPreNlsCreditInfoVo.getRecommenderOrgid());
            // 审批结果标志
//            nlsPsdPreCreditResultQueryRespBean.setAprvlRsltFlg(queryPreNlsCreditInfoVo.getApprovalResultMark());
            // 审批状态
            nlsPsdPreCreditResultQueryRespBean.setAprvSt(queryPreNlsCreditInfoVo.getStatus());
            // 授信建议额度
            BigDecimal reAmount = Optional.ofNullable(queryPreNlsCreditInfoVo.getReAmount()).orElse(BigDecimal.ZERO);
            nlsPsdPreCreditResultQueryRespBean.setCrRcmndnAmt(reAmount.doubleValue());
            // 建议年利率
            BigDecimal reYRate = Optional.ofNullable(queryPreNlsCreditInfoVo.getReYRate()).orElse(BigDecimal.ZERO);
            nlsPsdPreCreditResultQueryRespBean.setPrpslAnulIntRt(reYRate.doubleValue());
            // 授信期限
            nlsPsdPreCreditResultQueryRespBean.setLoanCrTrm(queryPreNlsCreditInfoVo.getCreditPeriod());
            // 授信期限单位
            nlsPsdPreCreditResultQueryRespBean.setLoanCrTrmUnit(queryPreNlsCreditInfoVo.getCreditPeriodUnit());
            // 法定代表人证件号
            nlsPsdPreCreditResultQueryRespBean.setCertNo(queryPreNlsCreditInfoVo.getCertNo());
            // 法定代表人手机号
            nlsPsdPreCreditResultQueryRespBean.setMblNo(queryPreNlsCreditInfoVo.getMobileNo());
            // 法定代表人姓名
            nlsPsdPreCreditResultQueryRespBean.setIdentNm(queryPreNlsCreditInfoVo.getCertName());
            // 法定代表人证件类型
            nlsPsdPreCreditResultQueryRespBean.setIdentTp(queryPreNlsCreditInfoVo.getCertType());
            // 拒绝原因
            nlsPsdPreCreditResultQueryRespBean.setRfsRsn(queryPreNlsCreditInfoVo.getRefuseReason());
            // 拒绝码
            nlsPsdPreCreditResultQueryRespBean.setRfsCd(queryPreNlsCreditInfoVo.getRefuseCode());
        }
        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                JSONObject.toJSONString(nlsPsdPreCreditResultQueryRespBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero),
                EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                EsbBizEnums.RetCodeMsg.SUCCESS_MSG.getVALUE());
    }

    /**
     * 需求编号：【2019D1218】（普税贷需求）
     * 问题编号：【2019D1218】（普税贷预授信申请信息查询失败返回信息）
     * 开发人员：【ludayong】
     * 创建日期：【2019/12/16 15:55】
     * 功能描述：
     * 修改日期：【2019/12/16 15:55】
     * 修改描述：
     */
    public EsbRespServiceBean failureHandler(EsbReqServiceBean esbReqServiceBean, NlsPsdPreCreditResultQueryRespBean nlsPsdPreCreditResultQueryRespBean, Exception exception, EsbRetCodeStandard esbRetCodeStandard) {
        logger.error("普税贷预授信申请信息查询接口出现异常，异常信息：" + exception.getMessage());
        nlsPsdPreCreditResultQueryRespBean.setRetCd(esbRetCodeStandard.getValue());
        nlsPsdPreCreditResultQueryRespBean.setRetMsg(exception.getMessage());
        exception.printStackTrace();
        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                JSONObject.toJSONString(nlsPsdPreCreditResultQueryRespBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteMapNullValue),
                EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                esbRetCodeStandard.getValue(),
                exception.getMessage());
    }

    //预授信申请信息表服务
    @Autowired
    @Qualifier("preNlsCreditInfoService")
    private PreNlsCreditInfoService preNlsCreditInfoService;
}